<template>
  <el-upload
    class="upload-demo"
    ref="uploadRef"
    :action="`${baseUrl}${uploadUrl}`"
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
    :on-error="handleError"
    :file-list="fileList"
    :accept="accept"
    :auto-upload="autoUpload"
    :disabled="disabled"
    :limit="limit"
    :show-file-list="false"
    :on-exceed="handleExceed"
  >
    <el-button slot="trigger" style="margin: 0 12px" icon="Upload">{{
      buttonText
    }}</el-button>
    <div slot="tip" class="el-upload__tip">{{ tip }}</div>
  </el-upload>
</template>

<script setup>
import { ref } from "vue";
const emit = defineEmits(["success", "error", "exceed", "before"]);

const baseUrl = ref(import.meta.env.VITE_BASE_URL);
const uploadRef = ref(null);
const props = defineProps({
  uploadUrl: {
    type: String,
    required: true,
  },
  accept: {
    type: String,
    default: ".xlsx,.xls",
  },
  buttonText: {
    type: String,
    default: "批量导入",
  },
  tip: {
    type: String,
    default: "",
  },
  autoUpload: {
    type: Boolean,
    default: true,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  limit: {
    type: Number,
    default: 1, // 默认限制上传一个文件
  },
});

const fileList = ref([]); // 文件列表，用于已上传的文件显示等操作

const handleSuccess = (response, file, fileList) => {
  emit("success", response, file, fileList); // 成功上传的回调函数，可以向外发送事件或处理数据等。
  uploadRef.value.clearFiles();
};

const beforeUpload = (file) => {
  // 这里可以添加文件类型检查等逻辑，返回 false 则停止上传。
  emit("before", file); // 或者根据需要返回 false 来阻止上传。
  return true; // 或者根据需要返回 false 来阻止上传。
};

const handleError = (err, file, fileList) => {
  emit("error", err, file, fileList); // 上传失败的回调函数。
};

const handleExceed = (files, fileList) => {
  emit("error", files, fileList); // 文件超出限制时的回调函数。
};
</script>
